﻿using ComTools.File;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using System;
using System.ServiceProcess;

namespace SuperSocketService
{
    partial class SuperSocketService : ServiceBase
    {
        /// <summary>
        /// 释放托管资源接口
        /// </summary>
        private IDisposable dis = null;

        public SuperSocketService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();

            LogHelper.WriteLog("初始化程序...");
            if (!bootstrap.Initialize())
            {
                LogHelper.WriteLog("初始化失败！");
                return;
            }
            LogHelper.WriteLog("启动中...");

            var result = bootstrap.Start();
            foreach (var server in bootstrap.AppServers)
            {
                switch (server.State)
                {
                    case ServerState.Running:
                        LogHelper.WriteLog($"{server.Name} 运行中");
                        break;
                    case ServerState.NotInitialized:
                        break;
                    case ServerState.Initializing:
                        break;
                    case ServerState.NotStarted:
                        break;
                    case ServerState.Starting:
                        break;
                    case ServerState.Stopping:
                        break;
                    default:
                        LogHelper.WriteLog($"{server.Name} 启动失败");
                        break;
                }
            }

            switch (result)
            {
                case StartResult.Failed:
                    LogHelper.WriteLog("无法启动服务，更多错误信息请查看日志");
                    break;
                case StartResult.None:
                    LogHelper.WriteLog("没有服务器配置，请检查你的配置！");
                    break;
                case StartResult.PartialSuccess:
                    LogHelper.WriteLog("一些服务启动成功，但是还有一些启动失败，更多错误信息请查看日志");
                    break;
                case StartResult.Success:
                    LogHelper.WriteLog("服务已经开始！");
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        /// <summary>
        /// 停止服务所需的关闭操作
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                if (dis != null)
                {
                    StopWindowsService("SuperSocketService");
                    dis.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString() + "释放webapi服务资源出现异常");
            }
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="serviceName"></param>
        public void StopWindowsService(string serviceName)
        {
            ServiceController[] scs = ServiceController.GetServices();
            foreach (ServiceController sc in scs)
            {
                if (sc.DisplayName == serviceName)
                {
                    try
                    {
                        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
                        sc.Stop();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
    }
}
